package com.kzl.android.activity;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.caucho.hessian.client.HessianProxyFactory;
import com.kzl.android.dao.BaseAPI;
import com.kzl.android.R;
import com.kzl.android.entity.request.HelloRequest;
import com.kzl.android.entity.response.HelloResponse;
import com.kzl.android.utils.GPUrls;

import java.net.MalformedURLException;

public class MyActivity extends Activity {
    private final String TAG = getClass().getName();
    private Toast toast;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        toast = Toast.makeText(this, "", Toast.LENGTH_LONG);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        findViewById(R.id.btn_hello).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new HttpNetTask().execute();
            }
        });
    }

    private class HttpNetTask extends AsyncTask<Void, Void, HelloResponse> {

        @Override
        protected HelloResponse doInBackground(Void... params) {
            HessianProxyFactory factory = new HessianProxyFactory();
            try {
                factory.setDebug(true);
                factory.setReadTimeout(5000);
                BaseAPI baseAPI = factory.create(BaseAPI.class, GPUrls.baseUrl, getClassLoader());
                HelloRequest helloRequest = new HelloRequest();
                helloRequest.setHellowords("hello world !!");
                return (HelloResponse) baseAPI.hello(helloRequest);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (Exception e) {
                Log.e(TAG, "exception,what's wrong");
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(HelloResponse response) {
            super.onPostExecute(response);
            toast.setText("调用结果:" + response.getHelloResponse());
            toast.show();
            Log.e(TAG, "调用结果:" + response);
        }
    }
}

